<?php

namespace Common\Logic;

/**
 * 预定端房卡部分
 * @modify trainyao 2016-05-11 创建
 */
class BookCardLogic extends \Common\Controller\BaseController {


    //获指定该用户拥有的有效订单下的所有用户
    public function getBrotherUsers($userId)
    {
        $orderInfoModel = D('OrderInfo');
        $orderList = $orderInfoModel->getInfoByUser($userId);
        if(empty($orderList))
        {
            return array();
        }
        //删除未入住订单，减少数据量
        foreach ($orderList as $k => $v)
        {
            if($v['status'] != ORDER_CHECKINED )
            {
                unset($orderList[$k]);
            }
        }
        unset($k);
        unset($v);
        $orderInfoIds = array_column($orderList, 'id');
        
        $orderRoomModel = D('OrderRoom');
        $orderRoomList = $orderRoomModel->getInfoByOrder($orderInfoIds);
        if(empty($orderRoomList))
        {
            return array();
        }
        //不考虑时区，删除明显过期的房间，严格删除后面另有判断，减少数据量
        foreach ($orderRoomList as $k => $v)
        {
            if(strtotime($v['enddate']) < strtotime("-2 day") )
            {
                unset($orderRoomList[$k]);
            }
        }
        unset($k);
        unset($v);  
        $orderRoomIds = array_column($orderRoomList, 'id');
        
        $userRoomModel = D('UserRoom');
        $userRoomList = $userRoomModel->getInfosByOrderRoom($orderRoomIds);
        if(empty($userRoomList))
        {
            return array();
        }
        $userRoomList = toGroupArray($userRoomList, 'orderroom_id');
        $result = array();
        foreach ($userRoomList as $k => $g)
        {
            if(is_array($g)&&!empty($g)&&!in_array($userId, array_column($g, 'userlogin_id')))
            {
                $g[0]['orderroom_id'] = "$k";
                $result[] = $g[0];
            }
        }
        return $result;
    }
    /**
     * 获取房卡列表
     * @modify trainyao 2016-05-11   创建
     * @param  integer   $userId      预定端用户ID
     * @return array                信息数组
     */
    public function getCard($userId) {
        
        $userRoomModel = D('UserRoom');
        $userRoomInfo = $userRoomModel->getInfoByUser($userId);
        if (empty($userRoomInfo)) {
            return array();
        }
        if(!empty($brotherUsers = $this->getBrotherUsers($userId)))
        {
            foreach ($brotherUsers as $b)
            {
                $userRoomInfo[] = $b;
            }
        }

        // 客栈时区
        $utc = new \Org\Util\UTC();
        $hotelEntityModel = D('HotelEntity');
        //获取区号时区数据
        $HotelLogic = A('Common/Hotel', 'Logic');
        $universalTimeData = $HotelLogic->universalTimeList();
        $universalTimeData = getArrayValueAsIndex($universalTimeData, 'universalTimeId');

        // 删除非已入住的状态的订单以及過期的訂單,顺便搜集客栈ID
        $orderRoomIds = array_column($userRoomInfo, 'orderroom_id');
        $hotelIds = array();
        $orderRoomModel = D('OrderRoom');
        $orderRooms = $orderRoomModel->getInfo($orderRoomIds);
        $orderRooms = getArrayValueAsIndex($orderRooms, 'id');

        
        $currentTimestamp = time();
        foreach ($userRoomInfo as $index => &$userRoomInfoItem) {
            if ($orderRooms[$userRoomInfoItem['orderroom_id']]['status'] != ORDER_CHECKINED) {
                unset($userRoomInfo[$index]);
                continue;
            } 
            //時區轉換
            $hotelInfo = $hotelEntityModel->getInfo($orderRooms[$userRoomInfoItem['orderroom_id']]['hotelentity_id']);
            $endTime = $userRoomInfoItem['enddate'];
            if ($hotelInfo['universaltime_id'] != 5) {
                $universalTimeTimezone = $universalTimeData[$hotelInfo['universaltime_id']]['universalTimeTimezone'];
                $endTime = $utc->toTimeZone($endTime, $universalTimeTimezone, 'Asia/Shanghai');
            }

            if (strtotime($endTime) < $currentTimestamp) {
                unset($userRoomInfo[$index]);
                continue;
            }
            $userRoomInfoItem['orderRoom'] = $orderRooms[$userRoomInfoItem['orderroom_id']];
            $userRoomInfoItem['hour'] = $orderRooms[$userRoomInfoItem['orderroom_id']]['hour'];
            array_push($hotelIds, $orderRooms[$userRoomInfoItem['orderroom_id']]['hotelentity_id']);
        }
        unset($userRoomInfoItem);
        if (empty($userRoomInfo)) {
            return array();
        }

        // 补充客栈预定信息
        $hotelIds = array_unique($hotelIds);
        $hotelDetailModel = D('HotelDetail');
        $hotelDetail = $hotelDetailModel->getInfoByHotel($hotelIds);
        if (count($hotelIds) == 1) {
            $hotelDetail = array($hotelDetail);
        }
        $hotelDetail = getArrayValueAsIndex($hotelDetail, 'hotelentity_id');

        foreach ($userRoomInfo as $index => &$userRoomInfoItem) {
            $hotelId = $orderRooms[$userRoomInfoItem['orderroom_id']]['hotelentity_id'];
            // 客栈没开通微预定,删除该房卡
            if (!isset($hotelDetail[$hotelId]) || $hotelDetail[$hotelId]['enable'] == DISABLE) {
                unset($userRoomInfo[$index]);
            } else {
                $userRoomInfoItem['hotelDetail'] = $hotelDetail[$hotelId];
            }
        }
        unset($userRoomInfoItem);
        // 补充房型封面
        //  获取房间信息,从而获取房型
        $roomIds = array_unique(array_column($userRoomInfo, 'roominfo_id'));
        $roomInfoModel = D('RoomInfo');
        $roomInfo = $roomInfoModel->getInfo($roomIds);
        if (count($roomIds) == 1) {
            $roomInfo = array($roomInfo);
        }
        $roomInfo = getArrayValueAsIndex($roomInfo, 'id');

        //  获取房型上架信息
        $roomTypeIds = array_unique(array_column($roomInfo, 'roomtype_id'));
        $roomTypeDetailModel = D('RoomTypeDetail');
        $roomTypeDetail = $roomTypeDetailModel->getInfoByRoomType(null, $roomTypeIds);
        if (count($roomTypeIds) == 1) {
            $roomTypeDetail = array($roomTypeDetail);
        }
        $roomTypeDetail = getArrayValueAsIndex($roomTypeDetail, 'roomtype_id');

        //  补充数据
        foreach ($userRoomInfo as $index => &$userRoomInfoItem) {
            // 不是锁掌柜同步的房间,删除该房卡
            if($roomInfo[$userRoomInfoItem['roominfo_id']]['roomfrom'] != ROOMFROM_QRM && $roomInfo[$userRoomInfoItem['roominfo_id']]['roomfrom'] != ROOMFROM_RFANDQRM ) {
                unset($userRoomInfo[$index]);
            } else {
                $roomTypeId = $roomInfo[$userRoomInfoItem['roominfo_id']]['roomtype_id'];
                $userRoomInfoItem['roomTypeCoverImageUrl'] = empty($roomTypeDetail[$roomTypeId]['coverimageurl']) ? '' : MEIZHU_URL . $roomTypeDetail[$roomTypeId]['coverimageurl'];
                $userRoomInfoItem['roomInfo'] = $roomInfo[$userRoomInfoItem['roominfo_id']];
            }
        }
        unset($userRoomInfoItem);

        return $userRoomInfo;
    }

    /**
     * 检查操作人是否能获取房卡
     * 方法会抛异常
     * @modify trainyao 2016-05-17    创建
     * @param integer $orderRoomId 子订单号
     * @param integer $userId      操作人id
     * @return boolean             是否能获取房卡
     */
    public function checkCanGetCard($orderRoomId, $userId) {
        $cardInfo = $this->getCard($userId);
        if (empty($cardInfo)) {
            throw new \Exception('403,601', 601);
            return false;
        }
        $cardInfo = getArrayValueAsIndex($cardInfo, 'orderroom_id');
        if (!isset($cardInfo[$orderRoomId])) {
            throw new \Exception('403,601', 601);
            return false;
        }

        // 检查是否到获取房卡时间
        $cardInfo = $cardInfo[$orderRoomId];
        $currentTimestamp = time();
        if ($currentTimestamp < strtotime($cardInfo['startdate'])) {
            throw new \Exception('403,602', 602);
            return false;
        }

        return $cardInfo;
    }
    /**
     * 分享房卡
     * @modify zhangzhen 2017-03-10    创建
     * @param integer $hotelId          
     * @param integer $orderRoomId     子订单号
     * @param integer $mobile          手机
     * @param integer $isLink          0->卡串 1->卡链
     * @return boolean             是否能获取房卡
     */
    public function shareCard($hotelId, $orderRoomId, $mobile, $isLink, $areaCode = '86', $opfrom = 0) {
        
        $shareCardRecordModel = D('ShareCardRecord');
        $shareCardRecordInfo = $shareCardRecordModel->getInfoByOrderRoomAndMobile($orderRoomId, $mobile, $areaCode);
        //如果存在分享记录，直接取出  
        if($shareCardRecordInfo) {
            $returnData = $this->getExistCard($shareCardRecordInfo['potentialauthorityid'], $isLink);
        } else {
            $returnData = $this->firstTimeGetCard($hotelId, $orderRoomId, $mobile, $isLink, $areaCode, $opfrom);
        }
        return $returnData;
    }

    /**
     * 获取已存在的卡
     * @modify zhangzhen 2017-03-10    创建
     * @param integer $potentialAuthorityId 卡ID     
     * @param integer $orderRoomId 子订单Id  
     * @param integer $isLink     0->卡串 1->卡链
     * @return string             是否能获取房卡
     */
    private function getExistCard($potentialAuthorityId, $isLink){
        if($isLink === '1') {
            $hashIdsUtil = new \Org\Util\Hashids(C('MEIZHU_HASHIDS_SALT'), 16);
            $potentialAuthorityHashId = $hashIdsUtil->encode($potentialAuthorityId);
            $url = shortenUrl('http://'.QRCLIENT_URL.'/meizhu?d=' . $potentialAuthorityHashId);
            return  $url;
        }
        
        if($isLink === '0'){
            //RPC生成房卡
            Vendor('phpRPC.phprpc_client');
            $client = new \PHPRPC_Client(C('MANAGE_QRCODE_URL'));
            $client->setEncryptMode(3);
            $sendData = array(
                'userId' => getUserId(),
                'from' => 3,
                'flag' => 'uclbrt',
                'time' => time(),
                'shareId' => $potentialAuthorityId,
            );
            $result = $client->getImageShareCard($sendData);
            $result = json_decode($result, true);
            if($result['httpstatus'] != 200){
                returnJson($result['httpstatus'], $result['status'], $result['info']);
            }
            return $result['data'];
                    
        }
    }

    /**
     * 第一获取卡
     * @modify zhangzhen 2017-03-10    创建
     * @param integer $hotelId     客栈    
     * @param integer $orderRoomId 子订单号 
     * @param integer $mobile      手机
     * @param integer $isLink      0->卡串 1->卡链
     * @return string              是否能获取房卡
     */
    private function firstTimeGetCard($hotelId, $orderRoomId, $mobile, $isLink, $areaCode = '86', $opfrom = 0){
        
        $hotelEntityModel = D('HotelEntity');
        $hotelEntityInfo = $hotelEntityModel->getInfo($hotelId); 
        if(empty($hotelEntityInfo)){
            returnJson(403, 402);
        }
        $communityNo = $hotelEntityInfo['communityno'];

        $userRoomModel = D('UserRoom');
        $userRoomInfos = $userRoomModel->getInfosByOrderRoom($orderRoomId);
        if(empty($userRoomInfos)){
            returnJson(403, 506);
        }
        $startTime = $userRoomInfos[0]['startdate'];
        $endTime = $userRoomInfos[0]['enddate'];

        $roomInfoModel = D('RoomInfo');
        $roomInfo = $roomInfoModel->getInfo($userRoomInfos[0]['roominfo_id']);
        if(empty($roomInfo)){
            returnJson(403, 301);
        }
        $roomNo = $roomInfo['name'];
        //RPC生成房卡
        Vendor('phpRPC.phprpc_client');
        $client = new \PHPRPC_Client(C('MANAGE_QRCLIENT_URL'));
        $client->setEncryptMode(3);
        $sendData = array(
            'userId' => getUserId(),
            'from' => 3,
            'flag' => 'uclbrt',
            'time' => time(),
            'communityNo' => $communityNo,
            'roomNo' => $roomNo,
            'mobile' => $mobile,
            'areaCode' => $areaCode,
            'orderRoomId' => $orderRoomId,
            'startTime' => $startTime,
            'endTime' => $endTime,
            'isLink' => $isLink
        );
        $result = $client->meizhuMakeShareCard($sendData);
        if(is_array($result) && $result['httpstatus'] == 200){ 
            if($isLink === '1'){
                $potentialAuthorityId = $result['data']; 
                //记录分享
                $shareCardRecordModel = D('ShareCardRecord');
                $shareCardRecordModel->addInfo($hotelId, $orderRoomId, $potentialAuthorityId, $mobile, $areaCode, $opfrom);

                //生成卡链接
                $hashIdsUtil = new \Org\Util\Hashids(C('MEIZHU_HASHIDS_SALT'), 16);
                $potentialAuthorityHashId = $hashIdsUtil->encode($potentialAuthorityId);
                $url = shortenUrl('http://'.QRCLIENT_URL.'/meizhu?d=' . $potentialAuthorityHashId);
                return $url;

            }elseif($isLink === '0'){
                $data = $result['data'];
                //记录分享
                $shareCardRecordModel = D('ShareCardRecord');
                $shareCardRecordModel->addInfo($hotelId, $orderRoomId, $data['potentialAuthorityId'], $mobile, $areaCode, $opfrom);
                //返回卡串
                return $data['cardString'];
            }else{
                returnJson(403, 202);
            }
        }elseif($result['httpstatus'] != 200){
            returnJson($result['httpstatus'], $result['status'], $result['info']);
        }else{
            returnJson(403, 202);
        }
    }
    
    public function deleteShareCard($orderRoomId, $mobile, $areaCode)
    {
        $shareCardRecordModel = D('ShareCardRecord');
        $shareCardRecordInfo = $shareCardRecordModel->getInfoByOrderRoomAndMobile($orderRoomId, $mobile, $areaCode);
        //如果存在分享记录，直接取出
        if(!empty($shareCardRecordInfo)) 
        {
            $shareCardRecordModel->deleteInfo($shareCardRecordInfo['id']);
            //RPC删除分享房卡
            Vendor('phpRPC.phprpc_client');
            $client = new \PHPRPC_Client(C('MANAGE_QRCLIENT_URL'));
            $client->setEncryptMode(3);
            $sendData = array(
                'from' => 3,
                'flag' => 'uclbrt',
                'time' => time(),
                'mobile' => $mobile,
                'areaCode' => $areaCode,
                'orderRoomId' => $orderRoomId
            );
            $result = $client->meizhuDeleteShareCard($sendData);
            if(!is_array($result)){
                return array(500, 500, var_export($result, true));
            }
            if($result['httpstatus'] != 200)
            {
                return array(500, 500, $result['data']);
            }
            return array(200, 200, 'success');
        }
        return array(500, 500, 'share record not exist');
    }
}
